package com.serverlite.framework.dao.core;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.serverlite.framework.utils.JsonUtils;

public class Page<T> {
    public static final int DEFAULT_PAGE_SIZE = 20;
    private int pageSize;
    private int pageIndex;
    private int pageTotal;
    private int totalCount;
    private List<T> data;

    public Page() {
        this.pageSize = 20;
    }

    public int getPageTotal() {
        return this.pageTotal;
    }

    public int getPageSize() {
        return this.pageSize;
    }

    public void setPageSize(int pageSize) {
        if (pageSize != this.pageSize) {
            this.pageSize = pageSize;
            caculate();
        }
    }

    public int getPageIndex() {
        return this.pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    public int getTotalCount() {
        return this.totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
        caculate();
    }

    public void setPageTotal(int pageTotal) {
        this.pageTotal = pageTotal;
    }

    public List<T> getData() {
        return this.data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }

    private void caculate() {
        if (this.pageSize != 0) {
            this.pageTotal = (this.totalCount / this.pageSize + ((this.totalCount
                    % this.pageSize > 0) ? 1 : 0));
        }
        if (this.pageTotal < 1)
            this.pageTotal = 1;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public JSONObject toJSON() {
        JSONObject o = new JSONObject();
        try {
            o.put("pageSize", pageSize);
            o.put("pageIndex", pageIndex);
            o.put("pageTotal", pageTotal);
            o.put("totalCount", totalCount);
            o.put("data", JsonUtils.listv2json(((List) data)));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return o;
    }

    @Override
    public String toString() {
        return toJSON().toString();
    }
}
